<template>
  <div class="security-page">
    <div class="security-header">
      <h2>安全设置</h2>
    </div>

    <div class="security-content">
      <!-- 头像设置区域 -->
      <div class="security-section">
        <div class="section-header">
          <h3>头像设置</h3>
        </div>
        <div class="section-content">
          <div class="avatar-section">
            <div class="avatar-preview">
              <img
                :src="userProfile.avatar_url || defaultAvatar"
                class="avatar-image"
                @error="handleAvatarError"
              />
            </div>
            <div class="avatar-controls">
              <input
                type="file"
                ref="avatarInput"
                accept="image/*"
                @change="handleAvatarChange"
                style="display: none"
              />
              <button class="upload-btn" @click="triggerAvatarUpload">选择图片</button>
              <button
                class="save-btn"
                @click="saveAvatar"
                :disabled="!selectedAvatar || isUploading"
              >
                {{ isUploading ? '上传中...' : '保存头像' }}
              </button>
              <p class="upload-hint">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 基本信息修改区域 -->
      <div class="security-section">
        <div class="section-header">
          <h3>基本信息</h3>
        </div>
        <div class="section-content">
          <form @submit.prevent="updateProfile" class="profile-form">
            <div class="form-group">
              <label>用户名</label>
              <input v-model="form.username" type="text" disabled class="form-control" />
            </div>

            <div class="form-group">
              <label>手机号</label>
              <input
                v-model="form.mobile"
                type="tel"
                class="form-control"
                placeholder="请输入手机号"
              />
            </div>

            <div class="form-group">
              <label>性别</label>
              <select v-model="form.gender" class="form-control">
                <option :value="0">未知</option>
                <option :value="1">男</option>
                <option :value="2">女</option>
              </select>
            </div>

            <div class="form-group">
              <label>生日</label>
              <input v-model="form.birthday" type="date" class="form-control" />
            </div>

            <div class="form-actions">
              <button type="submit" class="save-btn" :disabled="isSaving">
                {{ isSaving ? '保存中...' : '保存信息' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useAuthStore } from '@/stores/useAuthStore'
import { userApi, type UserProfile, getGenderText, formatDateTime } from '@/api/user'
import { ElMessage } from 'element-plus'

// 状态管理
const authStore = useAuthStore()

// 响应式数据
const userProfile = ref<UserProfile>({
  user_id: 0,
  username: '',
  email: '',
  mobile: '',
  gender: 0,
  avatar: '',
  avatar_url: '',
  birthday: '',
  status: 1,
  last_login_time: '',
  is_staff: false,
  is_active: true,
  date_joined: '',
})

const form = reactive({
  mobile: '',
  gender: 0,
  birthday: '',
  username: '',
})

const selectedAvatar = ref<File | null>(null)
const avatarInput = ref<HTMLInputElement | null>(null)
const isUploading = ref(false)
const isSaving = ref(false)
const defaultAvatar = ref('')

// 方法
const fetchUserProfile = async () => {
  try {
    const profile = await userApi.getUserProfile()
    userProfile.value = profile
    form.mobile = profile.mobile
    form.gender = profile.gender
    form.birthday = profile.birthday
    form.username = profile.username
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

const triggerAvatarUpload = () => {
  if (avatarInput.value) {
    avatarInput.value.click()
  }
}

const handleAvatarChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return
    }

    // 验证文件大小 (2MB)
    if (file.size > 2 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过 2MB')
      return
    }

    selectedAvatar.value = file
  }
}

const handleAvatarError = (event: Event) => {
  const img = event.target as HTMLImageElement
  // 防止重复尝试加载失败的图片
  if (img.src !== defaultAvatar.value) {
    // 当图片加载失败时，设置为空字符串，让CSS处理默认显示
    img.src = ''
  }
}

const saveAvatar = async () => {
  if (!selectedAvatar.value) {
    ElMessage.warning('请先选择头像图片')
    return
  }

  try {
    isUploading.value = true

    // 创建 FormData 对象
    const formData = new FormData()
    formData.append('avatar', selectedAvatar.value)

    // 调用更新头像接口
    const response = await userApi.updateAvatar(formData)

    // 更新用户信息
    await fetchUserProfile()

    // 更新认证存储中的头像URL
    if (authStore.user) {
      authStore.user.avatar = response.avatar_url
    }

    ElMessage.success('头像更新成功')
    selectedAvatar.value = null
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败: ' + (error as Error).message)
  } finally {
    isUploading.value = false
  }
}

const updateProfile = async () => {
  try {
    isSaving.value = true

    // 构造更新参数
    const params = {
      mobile: form.mobile,
      gender: form.gender,
      birthday: form.birthday,
    }

    // 调用更新用户信息接口
    await userApi.updateUserProfile(params)

    // 更新用户信息
    await fetchUserProfile()

    ElMessage.success('个人信息更新成功')
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败: ' + (error as Error).message)
  } finally {
    isSaving.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchUserProfile()
})
</script>

<style scoped lang="scss">
.security-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;

  .security-header {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    h2 {
      font-size: 24px;
      margin: 0;
      color: #333;
    }
  }

  .security-content {
    .security-section {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
      overflow: hidden;

      .section-header {
        padding: 20px;
        border-bottom: 1px solid #eee;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;

        h3 {
          margin: 0;
          font-size: 18px;
        }
      }

      .section-content {
        padding: 20px;

        .avatar-section {
          display: flex;
          align-items: center;
          gap: 30px;

          .avatar-preview {
            .avatar-image {
              width: 100px;
              height: 100px;
              border-radius: 50%;
              object-fit: cover;
              border: 2px solid #eee;
              // 当图片为空或加载失败时显示默认背景
              background-color: #ccc;
            }
          }

          .avatar-controls {
            flex: 1;

            .upload-btn,
            .save-btn {
              padding: 10px 20px;
              border: none;
              border-radius: 4px;
              font-size: 14px;
              cursor: pointer;
              margin-right: 10px;
              transition: all 0.3s;
            }

            .upload-btn {
              background-color: #f5f5f5;
              color: #666;

              &:hover {
                background-color: #e6e6e6;
              }
            }

            .save-btn {
              background-color: #409eff;
              color: white;

              &:hover:not(:disabled) {
                background-color: #3080e0;
              }

              &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
              }
            }

            .upload-hint {
              color: #999;
              font-size: 12px;
              margin-top: 10px;
            }
          }
        }

        .profile-form {
          .form-group {
            margin-bottom: 20px;

            label {
              display: block;
              margin-bottom: 8px;
              font-weight: 500;
              color: #333;
            }

            .form-control {
              width: 100%;
              padding: 12px 15px;
              border: 1px solid #ddd;
              border-radius: 4px;
              font-size: 16px;
              transition: all 0.3s;

              &:focus {
                outline: none;
                border-color: #409eff;
                box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
              }

              &:disabled {
                background-color: #f5f5f5;
                cursor: not-allowed;
              }
            }
          }

          .form-actions {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;

            .save-btn {
              padding: 12px 30px;
              background-color: #409eff;
              color: white;
              border: none;
              border-radius: 4px;
              font-size: 16px;
              cursor: pointer;
              transition: all 0.3s;

              &:hover:not(:disabled) {
                background-color: #3080e0;
              }

              &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
              }
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .security-page {
    padding: 10px;

    .security-content {
      .security-section {
        .section-content {
          .avatar-section {
            flex-direction: column;
            text-align: center;

            .avatar-controls {
              .upload-btn,
              .save-btn {
                margin-right: 0;
                margin-bottom: 10px;
                width: 100%;
              }
            }
          }
        }
      }
    }
  }
}
</style>
